package com.example.Controller;
import com.example.mapper.UserMapper;

import com.example.pojo.Result;
import com.example.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class FileUploadController {

    @Autowired
    private UserMapper userMapper;

    @PostMapping("/upload")
    public Result<String> upload(@RequestParam("file") MultipartFile file,
                                 @RequestParam("phone") String phone) throws Exception {
        // 获取文件原始名 + 唯一标识
        String originalFilename = file.getOriginalFilename();
        String filename = UUID.randomUUID().toString() +
                originalFilename.substring(originalFilename.lastIndexOf("."));

        // 上传文件至阿里云 OSS
        String url = AliOssUtil.uploadFile(filename, file.getInputStream());

        // 更新数据库中的头像地址
        int rows = userMapper.updateUserPicByPhone(phone, url);
        if (rows == 0) {
            return Result.error("更新失败，手机号不存在");
        }

        return Result.success(url);
    }
}
